let s_width = 1080;
let s_height = 2340;

setScreenMetrics(s_width, s_height);

function main() {
  let n = 0;
  while (++n) {
    clickDoor();
    toast("点击传送门");
    startDuel();
    toast("决斗开始");
    toast("等待");
    skip(15);
    for (let i = 1; true; i++) {
      //chouka();
      toast("放置怪兽");
      setM();
      toast("进入战阶");
      nextTime();
      toast("攻击");
      if (attck(i)) {
        toast("战斗结束");
        break;
      }
      toast("结束回合");
      nextTime();
      toast("等待");
      skip(20);
    }
    toast("跳过结算");
    skipOver();
    toast("结束" + n + "轮");
  }
}

function skip(times) {
  for (let i = 0; i < times; i++) {
    sleep(650);
    click(540, 1700);
  }
}

function clickDoor() {
  sleep(2000);
  click(820, 1000);
}

function startDuel() {
  //sleep(5000);
  //click(540, 2100);
  //sleep(5000);
  //click(540, 2100);
  while (true) {
    if (isDuel() && isDuel()) {
      break;
    }
    click(540, 2100);
  }
}

function chouka() {
  sleep(1000);
  click(540, 1170);
}

function setM() {
  skip(3);
  sleep(1000);
  swipe(540, 2200, 540, 1170, 700);
  sleep(1000);
  click(400, 1850);
  skip(3);
}

function attck(x) {
  toast("第" + x + "回合攻击");
  swipe(540, 1350, 540, 700, 400);
  if (x > 1) {
    skip(6);
    sleep(500);
    swipe(765, 1350, 540, 700, 400);
    if (x == 2) {
      skip(6);
      return isWin();
    }
  }
  if (x > 2) {
    skip(6);
    sleep(500);
    swipe(315, 1350, 540, 700, 400);
    return isWin();
  }
  return false;
}

function nextTime() {
  sleep(1000);
  click(1000, 1700);
  sleep(500);
  click(1000, 1700);
  sleep(1500);
}

function skipOver() {
  for (let i = 0; i < 15; i++) {
    sleep(650);
    click(540, 2250);
  }
  skip(15);
}

function isWin() {
  skip(6);
  //sleep(3000);
  //click(540, 2240);
  toast("测试战斗是否结束");
  let img = captureScreen();
  //images.save(img,"./1.jpg");
  //console.log(images.pixel(img,540,2240));
  let b = images.detectsColor(img, -1, 540, 2240);
  return b;
}

function isDuel() {
  sleep(700);
  //click(1000,190);
  let img = captureScreen();
  //images.save(img,"./1.jpg");
  //console.log(images.pixel(img,1000,190));
  let b = images.detectsColor(img, -1, 1000, 190);
  return b;
}

images.requestScreenCapture();
main();
